# configure-start.pm
# Copyright (C) 2006  Stephane Alnet
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
# 

#
# For more information: http://carrierclass.net/
#
package CCNCore::Provision::Start;
use strict; use warnings;
use CCNCore::Provision::Base;
use base qw(CCNCore::Provision::Base);
use CCN::Text;
use CCNCore::Scripting;
use CCNCore::Home;

sub run()
{
    my $self = shift;
    return if $self->p->force_manager;
    
    $self->PACKAGE ('openssh-client');
    $self->CHECKFOR ('/etc/ssh');
    $self->CHECKFOR ('/usr/bin/ssh');
    $self->enable('ssh');

    $self->PACKAGE ('openssh-server');
    $self->CHECKFOR ('/usr/sbin/sshd');

    $self->CHECKFOR (CCNCore::Home::config.'/local');
    $self->CHECKFOR (CCNCore::Home::manager.'/bin');

    # By default Debian installs inetd with in.tftpd, which breaks
    # running tftpd-hpa as a daemon.
    CAT '/etc/inetd.conf', "# This file intentionally left blank by the CarrierClass.net Management System.\n";

    # --- Identify what services we run
    # TBD remove portmap, rpc.statd, exim as inbound MTA

    # This list is initally for FC4.
    for my $service (qw( rpcidmapd rpcgssd portmap nfslock cups xinetd inetd openbsd-inetd gpm pcmcia isdn xfs netfs bluetooth anacron ))
    {
        $self->disable($service);
    }
    
    # PACKAGE("watchdog");

    # Generate a PEM for the local server if none already exists.
    CCN::Scripting::exec_command(CCNCore::Home::manager.q(/lib/CCNCore/bin/bootstrap/generate-pem.sh ').$self->p->server_name.q(' 370));

    ## YYYPORT Does the "invoke-rc.d" piece exist/work under RH-based systems?
    ## No, use chkconfig for that. (Check on an actual CentOS though.)

    # logrotate runs from crontab
    # This list used to include /var/log/asterisk/cdr-csv/Master.csv but does not anymore
    # since it gets rotated from within local/billing.sh.
    # YYYPORT This only works for Debian? ("logger-reload"? "asterisk asterisk")
    CAT '/etc/logrotate.d/asterisk', <<'EOT';
/var/log/asterisk/full /var/log/asterisk/event_log /var/log/asterisk/messages {
    missingok
    daily
    rotate 2
    create 0660 asterisk asterisk
    sharedscripts
    postrotate
        /usr/sbin/invoke-rc.d asterisk logger-reload
    endscript
}
EOT
    # The rotation itself is done by the mysql-server logrotate profile (on Debian, at least)
    CAT '/etc/logrotate.d/ccn-mysql', <<'EOT';
/var/log/mysql/queries /var/log/mysql/queries.slow {
    missingok
    daily
    rotate 2
    create 0660 mysql adm
}
EOT

    # YYYPORT logcheck does not exist on CentOS, what about RHE, FC?
    if($self->p->operating_system =~ /^(debian|ccn)/) {

        # TBD Do we actually require logcheck?
        # - # CHECKFOR ('/etc/logcheck/logcheck.logfiles');

        # ENABLE 'logcheck';

        if( open my $fh, '<', '/etc/logcheck/logcheck.logfiles' )
        {
            local $/;
            my $content = <$fh>;
            close $fh;
            if( $content !~ m{^/var/log/asterisk/messages$}g )
            {
                CAT '/etc/logcheck/logcheck.logfiles', $content."/var/log/asterisk/messages\n";
                IF_CHANGED '/etc/logcheck/logcheck.logfiles' => ''; # Runs from crontab
            }
        }
        else
        {
            $self->warn ("open(logcheck.logfiles): $!");
        }
    }

    # Management Timezone setup
    $self->CHECKFOR ('/etc/timezone');
    my $tz = $self->sql_get(q(SELECT timezone FROM systems WHERE id = ?),$self->p->system_pk);
    $tz = 'UTC' if not defined $tz;
    return $self->error ("Unknown timezone $tz; please specify a valid system-wide timezone.")
        unless -e "/usr/share/zoneinfo/$tz";
    CAT '/etc/timezone', "$tz\n";

    # TBD Probably need to restart a few things here... What??
    CCNv2::Scripting::IF_CHANGED_restart_asterisk('/etc/timezone') if $self->p->{cp_member};

    $self->CHECKFOR ('/etc/localtime');

    # No need to wait for commit() to run these.
    if( $self->upgrading )
    {
        # Install our own rc-local script in /etc/rc.local.
        CCN::Scripting::exec_command(CCNCore::Home::manager.q(/lib/CCNCore/bin/bootstrap/rclocal-install.sh));

        # Install "static" content at bootstrap or during an upgrade.
        # Note: This used to be done after mysql was started and before db_ser.
        CCN::Scripting::exec_command(CCNCore::Home::manager.'/bin/upgrade/upgrade-chmod.sh');

        # Remove updatedb's automated updates
        CCN::Scripting::exec_command(q(/bin/rm -f "/etc/cron.daily/find"));

        # Note that q(update-inetd --multi --remove '.') may do the same thing?
        CCN::Scripting::exec_command('/etc/init.d/inetd stop; /etc/init.d/openbsd-inetd stop; /etc/init.d/xinetd stop; echo');

    } # /if upgrading

    if( defined $self->p->{cp_cluster} )
    {
        if( $self->upgrading || ! -d '/etc/asterisk/config' )
        {
            CCN::Scripting::exec_command CCNCore::Home::manager.'/lib/CCNv2/bin/upgrade/upgrade-asterisk.sh';
        }
        CCN::Scripting::exec_command CCNCore::Home::manager.'/lib/CCNv2/bin/upgrade/upgrade-asterisk-dirs.pl';
    }
    COMMIT_MODULE(ref($self));
}

sub commit()
{
    my $self = shift;
    my $c = shift;

    $c->run_if_changed('/etc/timezone' , '/bin/rm -f /etc/localtime.prev');
    $c->run_if_changed('/etc/timezone' , '/bin/mv /etc/localtime /etc/localtime.prev');
    $c->run_if_changed('/etc/timezone' , "/bin/ln -s /usr/share/zoneinfo/`/bin/cat /etc/timezone` /etc/localtime");
    
    CCN::Scripting::exec_command CCNCore::Home::manager.'/bin/provision/crontab-clear.sh';
}

1;